/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import dbs.Friend;
import dbs.User;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;

/**
 *
 */
@Stateless
@LocalBean
public class AuthBean {

    @EJB
    private UserFacade userFacade;
    
    @EJB
    private FriendFacade friendFacade;
    
    /**
     *  set name, gcmKey and friends. <br>
     *  If there is no user, sign up by inserting new user.
     * 
     * @param facebookID
     * @param name
     * @param gcmKey
     * @param friendIDList
     * @return if failed, return false.
     */
    public boolean singUp(long facebookID, String name, String gcmKey, List<Long> friendIDList){    
        User user = userFacade.findUser(facebookID);
        
        if(user == null)
        {
            User newUser = new User(facebookID);
            userFacade.create(newUser);
            
            user = newUser;
        }
        
        System.out.println(user);
        
        user.setName(name);
        user.setGCMkey(gcmKey);
        userFacade.edit(user);
        
        // set friend list
        for(long friendID : friendIDList)
        {
            Friend friend = friendFacade.findFriendData(facebookID, friendID);

            if(friend == null)
            {
                Friend newFriend = new Friend(facebookID, friendID);
                Friend newFriend_symmetric = new Friend(friendID, facebookID);

                try
                {
                    friendFacade.create(newFriend);
                    friendFacade.create(newFriend_symmetric);
                }
                catch(Exception e)
                {
                    
                }
            }
        }
        
        return true;
    }
    
    /**
     * check auth.
     * 
     * @param facebookId
     * @param gcmKey
     * @return 
     */
    public boolean auth(long facebookId, String gcmKey)
    {
        User user = userFacade.findUser(facebookId);
        
        if(user == null)
        {
            return false;
        }
        
        System.out.println(user.getGCMkey());
        System.out.println(gcmKey);
        
        return user.getGCMkey().equals(gcmKey);
    }
}
